'use strict';

const Service = require('egg').Service;

class OrderService extends Service {
    async getOrders() {
        const { app, service } = this;
        const order = await app.mysql.select('order');
        let orderId = order.map(item => item.good_id);
        orderId = { id: orderId }
        let goods = await app.mysql.select('goods', {
            where: orderId
        });
        goods = goods.map((item) => {
            let itemBase = item;
            order.map(item => {
                if (item.good_id === itemBase.id) {
                    itemBase.num = item.num;
                }
            });
            return itemBase;
        })
        let shopId = goods.map(item => item.shop_id);
        shopId = service.order.deweighting(shopId);
        let shop = await app.mysql.select('shop', {
            where: { id: shopId }
        });
        shop = shop.map((item) => {
            let itemBase = item;
            itemBase.data = goods.filter(item => item.shop_id === itemBase.id);
            return itemBase;
        });
        return shop;
    }
    // 去重
    deweighting(arr = []) {
        let arrBase = [];
        arr.map(item => {
            arrBase.indexOf(item) === -1 ? arrBase.push(item) : '';
        });
        return arrBase;
    }
    async upDateOrder(good_id, num) {
        const { app } = this;
        const result = await app.mysql.update('order', { num }, { where: { good_id } });
        return result;
    }
    async deleteOrder(ids) {
        const { app } = this;
        const result = await app.mysql.delete('order', { good_id:ids });
        return result;
    }
    async getOrder(id) {
        const { app } = this;
        const result = await app.mysql.select('order', { where: { good_id: id } });
        return result;
    }
    async addOrder(good_id, num) {
        const { app } = this;
        const result = await app.mysql.insert('order', { good_id, num });
        return result;
    }
}

module.exports = OrderService;
